var Ui =
{
    assertJid: function(jid, functionName)
    {
        if (Ui.isContact(jid) == false)
        {
            // throw new Error(functionName + ": invalid jid: " + jid);
            log("**** WARNING: " + functionName + ": invalid jid: " + jid);
        }
    },

    getUserJid: function()
    {
       return $("#username").val();
    },

    getUserPassword: function()
    {
       return $("#password").val();
    },

    getIdFromJid: function (jid)
    {
        return Strophe.getBareJidFromJid(jid).replace("@", "-").replace(/\./g, "-");
    },

    createContactListItem: function(jid, name, presenceShow, presenceStatus)
    {
        var jid_id = Ui.getIdFromJid(jid);

        if (presenceShow === undefined || presenceShow === null)
            presenceShow = "xa";

        if (presenceStatus === undefined || presenceStatus === null)
            presenceStatus = "";

        var contactListItem = $("<li id='" + jid_id + "'>" +
                                    "<div class='roster-contact " + presenceShow + "'>" +
                                        "<div class='roster-name'>" + name + "</div>" +
                                        "<div class='roster-jid'>" + Strophe.getBareJidFromJid(jid) + "</div>" +
                                        "<div class='roster-show'>" + presenceShow + "</div>" +
                                        "<div class='roster-status'>" + presenceStatus + "</div>" +
                                    "</div>" +
                                "</li>");

        return contactListItem;
    },

    removeAllContacts: function()
    {
        $("#roster-area li").remove();
    },

    setContactPresenceStatus: function(jid, presenceStatus)
    {
        Ui.assertJid(jid, "setContactPresenceStatus");

        var success = false;
        if (Ui.isContact(jid) == true)
        {
            var jidId = Ui.getIdFromJid(jid);
            var contactStatus = $('#roster-area li#' + jidId + ' .roster-status');
            contactStatus.text(presenceStatus);
            success = true;
        }
        return success;
    },

    setContactPresenceShow: function(jid, presenceShow)
    {
        Ui.assertJid(jid, "setContactPresenceShow");

        var success = false;
        if (Ui.isContact(jid) == true)
        {
            var jidId = Ui.getIdFromJid(jid);
            var name = Ui.getContactName(jidId);
            var presenceStatus = Ui.getContactPresenceStatus(jid);
            $('#roster-area li#' + jidId).remove();
            Ui.insertContact(jid, name, presenceShow, presenceStatus);
            success = true;
        }
        return success;
    },

    getContactName: function(jid)
    {
        Ui.assertJid(jid, "getContactName");

        if (Ui.isContact(jid) == true)
        {
            var jid_id = Ui.getIdFromJid(jid);
            return $("#roster-area li#" + jid_id + " .roster-name").text();
        }
        return "";
    },

    getContactPresenceShow: function(jid)
    {
        Ui.assertJid(jid, "getContactPresenceShow");

        if (Ui.isContact(jid) == true)
        {
            var jidId = Ui.getIdFromJid(jid);
            var contact = $('#roster-area li#' + jidId + ' .roster-contact');
            for (var show_value in Xmpp.show_values)
            {
                if (contact.hasClass(Xmpp.show_values[show_value]))
                    return Xmpp.show_values[show_value];
                ++show_value;
            }
        }
        return Xmpp.show_values[0];
    },

    getContactPresenceShowValue : function(presenceShow)
    {
        var show_value = 0;
        if (typeof presenceShow === "object")
        {
            for (show_value in Xmpp.show_values)
            {
                if (presenceShow.hasClass(Xmpp.show_values[show_value]))
                    return show_value;
                ++show_value;
            }
        }
        else if (typeof presenceShow === "string")
        {
            for (show_value in Xmpp.show_values)
            {
                if (presenceShow === Xmpp.show_values[show_value])
                    return show_value;
                ++show_value;
            }
        }
        return 0;
    },

    getContactPresenceStatus: function(jid)
    {
        Ui.assertJid(jid, "getContactPresenceStatus");

        if (Ui.isContact(jid) == true)
        {
            var jid_id = Ui.getIdFromJid(jid);
            return $("#roster-area li#" + jid_id + " .roster-status").text();
        }
        return "";
    },

    isContact: function(jid)
    {
        var jidId = Ui.getIdFromJid(jid);
        return $("#" + jidId).length > 0 ? true : false ;
    },

    replaceContact: function(jid, name)
    {
        Ui.assertJid(jid, "replaceContact");

        var success = false;
        if (Ui.isContact(jid) == true)
        {
            var show = Ui.getContactPresenceShow(jid);
            var status = Ui.getContactPresenceStatus(jid);
            var contactListItem = Ui.createContactListItem(jid, name, show, status);
            var jidId = Ui.getIdFromJid(jid);
            $("#" + jidId).replaceWith(contactListItem);
            success = true;
        }
        return success;
    },

    removeContact: function(jid)
    {
        Ui.assertJid(jid, "removeContact");

        var success = false;
        if (Ui.isContact(jid) == true)
        {
            var jidId = Ui.getIdFromJid(jid);
            $("#" + jidId).remove();
            success = true;
        }
        return success;
    },

    insertContact : function(jid, name, show, status)
    {
        log ("Ui.insertContact : jid: " + jid + " name: " + name + " show: " + show + " status: " + status);

        var inserted = false;
        if (Ui.isContact(jid) == false)
        {
            var jidId = Ui.getIdFromJid(jid);
            var contactListItem = Ui.createContactListItem(jid, name, show, status);
            var showValue = Ui.getContactPresenceShowValue(show);
            var contacts = $('#roster-area li');
            if (contacts.length > 0)
            {
                contacts.each
                (
                    function()
                    {
                        var itemShow = Ui.getContactPresenceShow($(this).attr("id"));
                    	var itemShowValue = Ui.getContactPresenceShowValue(itemShow);
                        var itemJid    = $(this).find('.roster-jid').text();
                        var itemJidId = Ui.getIdFromJid(itemJid);

                        if ((itemShowValue === showValue && jidId < itemJidId) || itemShowValue < showValue)
                        {
                            $(this).before(contactListItem);
                            inserted = true;
                            return false;
                        }
                        return true;
                    }
                );

                if (!inserted)
                {
                    $('#roster-area ul').append(contactListItem);
                    inserted = true;
                }
            }
            else
            {
                $('#roster-area ul').append(contactListItem);
                inserted = true;
            }
        }

        return inserted;
    },

    setChatTabData: function(jid)
    {
        var success = false;
        if (Ui.isChattingWith(jid))
        {
            var jid_id = Ui.getIdFromJid(jid);
            var user_chat_tab_id = "#chat-" + jid_id;
            $(user_chat_tab_id).data("jid", jid);
            $(user_chat_tab_id + " input.chat-text-input").attr("jid", jid);
            success = true;
            
        }
        return success;
    },
    
    createChatTab: function (jid, name)
    {
        var jid_id = Ui.getIdFromJid(jid);
        var user_chat_tab_id = "#chat-" + jid_id;

        $("#main_tabs").tabs("add", user_chat_tab_id, name);
        $(user_chat_tab_id).append
        (
            "<div class='chat-messages'></div>" +
            "<div class='chat-input'>" +
                "<input class='chat-text-input' type='text' jid='" + jid + "'></input>" +
            "</div>"    
        );

        Ui.setChatTabData(jid);

        var margins = 0;
        var paddings = 15;

        $("#main_tabs").css("margin", "0px");
        $("#main_tabs").css("padding", "0px");

        $(".ui-tabs-panel").css("margin", "0px");
        $(".ui-tabs-panel").css("padding", "0px");
        var tabsPanelWidth = $("#main_tabs").width() - 2 * (paddings + margins);

        $(".chat-input").css("margin", margins + "px");
        $(".chat-input").css("padding", paddings + "px");
        $(".chat-input").css("border-style", "solid none none");
        $(".chat-input").css("width", tabsPanelWidth + "px");
        $(".chat-input").css("height", "2em");
        $(".chat-input").css("background", "none");

        $(".chat-text-input").css("width", tabsPanelWidth + "px");
        
        $(".chat-messages").css("margin", margins);
        $(".chat-messages").css("padding", paddings);
        $(".chat-messages").css("border-style", "none");
        $(".chat-messages").css("width", tabsPanelWidth + "px");
        $(".chat-messages").css("overflow", "scroll");

        var mainPanelHeight = $("#main_tabs").height();
        var tabsHeight = $(".ui-tabs-nav").height();
        var inputHeight = $(".chat-input").height();
        var messageDivHeight = mainPanelHeight - tabsHeight - inputHeight - 4 * (margins + paddings);

        $(".chat-messages").css("height", messageDivHeight + "px");
    },

    selectChatTab: function(jid)
    {
        var jid_id = Ui.getIdFromJid(jid);
        var user_chat_tab_id = "#chat-" + jid_id;
        $("#main_tabs").tabs("select", user_chat_tab_id);
        $(user_chat_tab_id + " input").focus();
    },

    appendChatMessage: function(isMe, jid, body_text, isDelayedMessage)
    {
        var jid_id = Ui.getIdFromJid(jid);
        var user_chat_tab_id = "#chat-" + jid_id;

        var messageContent = $("<div class='chat-message-" + (isMe? "myself" : "other") + "'" + (isDelayedMessage ? " delayed " : "") + ">" +
                                    "&lt;<span class='chat-name'>" +
                                        (isMe ? "myself" : Strophe.getNodeFromJid(jid)) +
                                    "</span>&gt;" +
                                    "<span class='chat-text'>" +
                                        body_text +
                                    "</span>" +
                               "</div>");

        $(user_chat_tab_id).parent().find(".chat-messages").append(messageContent);
    },

    scrollChat: function(jid)
    {
        var jid_id = Ui.getIdFromJid(jid);
        var user_chat_messages = "#chat-" + jid_id + " .chat-messages";
        log("number of chat messages : " + $(user_chat_messages).length);
        var domDiv = $(user_chat_messages).get(0);
        domDiv.scrollTop = domDiv.scrollHeight;
    },

    isChattingWith: function(jid)
    {
        var jid_id = Ui.getIdFromJid(jid);
        var user_chat_tab_id = "#chat-" + jid_id;
        return ($(user_chat_tab_id).length > 0) ? true : false ;
    },

    showContacts: function()
    {
        $("#accordion1").accordion( "activate" , "#buddies" );
    },

    showPresenceRequestApprovalDialog: function(requesterJid)
    {
        log("Ui.showPresenceRequestApprovalDialog: startging. requesterJid : " + requesterJid);

        $("#approveJid").text(requesterJid);
        $("#approveDialog").dialog("open");

        log("Ui.showPresenceRequestApprovalDialog: exiting.");
    }
};

$(function()
{
	// For debug purposes only
    $("#username").val("guysagy@jabber.org")
    $("#password").val("")

/*
    // Left hand screen area accordion.
    $("#main_accordion").accordion({header: "h3",  fillSpace: true});
    var accordionHeader = $(".ui-accordion-header");
    var accordionHeaderHeight = accordionHeader.height();
    $("#main_accordion").css("height", 500 - accordionHeaderHeight); // TODO: revisit .... 
    $("#main_accordion").accordion("resize");
*/
    // Right hand screen area tabs.
    $('#main_tabs').tabs().find('.ui-tabs-nav').sortable({axis: 'x'}); 
    //$("#main_tabs").css("height", $("#main_tabs").parent().height() + "px"); 
    $("#main_tabs").tabs("resize");
    $("#main_tabs").css("border", "none");

    $("#connection_destroy").addClass("hidden");
    $("button#xmpp_connect").click(Xmpp.connect);
    $("button#xmpp_disconnect").click(Xmpp.disconnect);

    $("#contactDialog").dialog
    (
        {
            autoOpen: false,
            draggable:true,
            modal:false,
            title:"Add a contact",
            buttons:
            {
                "Add" : function()
                {
                    Xmpp.add_contact({jid:$("#contactId").val(), name:$("#contactName").val()});
                    $("#contactId").val("");
                    $("#contactName").val("");
                    $(this).dialog("close");
                }
            }
        }
    );

    $("button#addContact").click
    (
       function()
       {
           $("#contactDialog").dialog("open");
       }
    );

    $("#approveDialog").dialog
    (
        {
            autoOpen: false,
            draggable: true,
            modal: false,
            title: "Subscription Request",
            buttons:
            {
               "Deny": function()
               {
                   log("approveDialog Deny: startging.");

                   Xmpp.connection.send($pres({to: Xmpp.pending_subscriber, type: "unsubscribed"}));
                   Xmpp.pending_subscriber = null;
                   $(this).dialog("close");

                   log("approveDialog Deny: exiting.");
               },

               "Approve": function()
               {
                   log("approveDialog Approve: startging.");
                   // Approve request.
                   Xmpp.connection.send($pres({to: Xmpp.pending_subscriber, type: "subscribed"}));

                   // Request other side's presence.... hmmm.... do this depending on a check box to be added to the dialog.
                   // Xmpp.connection.send($pres({to: Xmpp.pending_subscriber, "type": "subscribe"}));
                   Xmpp.pending_subscriber = null;
                   $(this).dialog("close");

                   log("approveDialog Approve: exiting.");
               }
            }
        }
    );

    $(".roster-contact").live
    (
        "click",
        function()
        {
            var jid = $(this).find(".roster-jid").text();
            var name = $(this).find(".roster-name").text();
            var jid_id = Ui.getIdFromJid(jid);
            var user_chat_tab_id = "#chat-" + jid_id;

            log("number of " + user_chat_tab_id + " tabs is : " + $(user_chat_tab_id).length);
            if (Ui.isChattingWith(jid) === false)
            {
                Ui.createChatTab(jid, name);
            }

            Ui.selectChatTab(jid);
        }
    );

    $(".chat-text-input").live(
        "keypress",
        function(event)
        {
            if (event.which === 13)
            {
                // Enter key has been pressed.
                event.preventDefault();
                var body_text = $(this).val();
                var jid = $(this).attr("jid"); // $(this).parent().data("jid");
                Xmpp.connection.send($msg({to: jid, type: "chat"}).c("body").t(body_text));
                Ui.appendChatMessage(true, jid, body_text, false);
                Ui.scrollChat(jid);
                $(this).val("");
            }
        }
    );
});